package com.eureka.gateway.configurer;

import com.eureka.bclass.base.BaseResult;
import com.eureka.bclass.util.LoggerUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: TODO 全局网关异常处理，只作用在webflux环境下, 优先级低于 { ResponseStatusExceptionHandler } 执行
 * @Author: lixing
 * @Date: 2021/6/26 17:26
 */
@Order(-1)
@Component
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper;

    public GlobalExceptionConfiguration(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(throwable);
        }

        // header set
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (throwable instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) throwable).getStatus());
        }

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                String errMsg = throwable.getMessage();
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(new BaseResult<String>().fail(errMsg)));
            } catch (JsonProcessingException e) {
                LoggerUtil.error(e.getMessage());
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }
}
